package com.ctc.lottery.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctc.lottery.common.BaseContext;
import com.ctc.lottery.entity.Indent;
import com.ctc.lottery.entity.Lottery;
import com.ctc.lottery.entity.Member;
import com.ctc.lottery.service.IndentService;
import com.ctc.lottery.service.LotteryService;
import com.ctc.lottery.service.MemberService;
import com.ctc.lottery.vo.MemberVo;
import com.ctc.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "会员管理")
@RestController
@RequestMapping(value = "/menber")
@Slf4j
public class MenberController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private LotteryService lotteryService;
    @Autowired
    private IndentService indentService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private Redisson redisson;

    @ApiOperation(value = "加入会员")
    @PostMapping(value = "/addMenber")
    public R addMenber(@RequestBody MemberVo memberVo) {
        Member one = memberService.getOne(new LambdaQueryWrapper<Member>().eq(Member::getName, memberVo.getName()));
        if (one!=null){
            return R.error().put("data","您已经加入了会员");
        }

        Member member = new Member();
        BeanUtils.copyProperties(memberVo,member);
        memberService.save(member);
        BaseContext.setCurrentUserName(member.getName());
        String uuid = "uesr-token:"+ UUID.randomUUID();
        redisTemplate.opsForValue().set(uuid,member.getEmail(),30, TimeUnit.MINUTES);

        String key = "lottery-"+ LocalDate.now();
        Long count = redisTemplate.opsForSet().add(key, member.getId());
        redisTemplate.expire(key, 8, TimeUnit.HOURS);

        return R.ok().put("data",uuid);
    }

    @ApiOperation(value = "会员登录")
    @PostMapping(value = "/login")
    public R login(String email, String password) {
        Member member = memberService.getOne(
                new LambdaQueryWrapper<Member>().eq(Member::getEmail, email).eq(Member::getPassword, password)
        );
        if (member==null){
            return R.error(402,"登录失败，用户名或密码错误");
        }
        BaseContext.setCurrentUserName(member.getName());
        String uuid = "uesr-token:"+ UUID.randomUUID();
        redisTemplate.opsForValue().set(uuid,email,30, TimeUnit.MINUTES);
        return R.ok().put("data",uuid);
    }

    @ApiOperation(value = "获取抽奖机会")
    @PostMapping(value = "/getLotteryChance")
    public R getLotteryChance(Long activityId) {
        // 查询该活动
        Lottery byId = lotteryService.getById(activityId);
        // 活动key值
        String key = "lottery:"+byId.getActivityName();
        // 该用户目前的抽奖次数
        String numStr = (String) redisTemplate.opsForHash().get(key, BaseContext.getCurrentUserName());
        int num = 0;
        if (numStr!=null){
            num = Integer.parseInt(numStr);
        }

        // 异常处理
        if (++num>5){
            return R.error(402,"您的抽奖次数已达到最大值");
        }
        long count = indentService.count(
                new LambdaQueryWrapper<Indent>().eq(Indent::getRemark, byId.getActivityName())
                        .eq(Indent::getMemberName, BaseContext.getCurrentUserName())
        );
        if (count>10){
            return R.error(402,"你已经有足够的抽奖次数了");
        }


        redisTemplate.opsForHash().put(key, BaseContext.getCurrentUserName(),String.valueOf(num));


        return R.ok().put("data","当前抽奖次数为:"+num);

    }
}
